package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Scanner;

/**
 * 演示通过反射机制实例化对象
 * 2.有参实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入类名：");
        String className =sc.nextLine();
        Class cls  = Class.forName(className);  //reflect.Person

        //Constructor是反射对象之一，它的每个实例用于表示一个类的构造器
        //获取Person的无参构造器
        Constructor constructor1 = cls.getConstructor();  //new Person()
        Object obj1 = constructor1.newInstance();
        System.out.println(obj1);

        //获取Person的String参构造器
        Constructor constructor2 = cls.getConstructor(String.class);
        Object obj2 = constructor2.newInstance("张三");
        System.out.println(obj2);

        //获取Person的String-int参构造器
        Constructor constructor3 = cls.getConstructor(String.class,int.class);
        Object obj3 = constructor3.newInstance("张三",30);
        System.out.println(obj3);

    }
}
